package com.gateway.security.handler;

import com.gateway.common.dto.PluginData;
import com.gateway.common.enums.PluginEnum;
import com.gateway.common.utils.JsonUtils;
import com.gateway.common.utils.Singleton;
import com.gateway.plugin.api.util.SpringBeanUtils;
import com.gateway.plugin.base.handler.PluginDataHandler;
import com.gateway.security.config.SecurityConfig;
import com.gateway.security.endpoint.TokenEndpointService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Objects;

/**
 * @program: api-gateway
 * @description:
 * @author: YuKai Fan
 * @create: 2025/2/10 23:16
 **/
public class SecurityPluginDataHandler implements PluginDataHandler {
    private static final Logger log = LoggerFactory.getLogger(SecurityPluginDataHandler.class);

    private final TokenEndpointService tokenEndpointService;

    public SecurityPluginDataHandler(TokenEndpointService tokenEndpointService) {
        this.tokenEndpointService = tokenEndpointService;
    }

    @Override
    public void handlerPlugin(PluginData pluginData) {
        if (Objects.isNull(pluginData) || Boolean.FALSE.equals(pluginData.getEnabled())) {
            log.info("the plugin {} is disabled", this.pluginNamed());
            return;
        }
        String config = pluginData.getConfig();
        SecurityConfig securityConfig = JsonUtils.stringToBean(config, SecurityConfig.class);
        if (Objects.isNull(securityConfig)) {
            log.info("invalid securityConfig.");
            return;
        }
        Singleton.INST.single(SecurityConfig.class, securityConfig);
        this.doRefreshConfig(securityConfig);
    }

    @Override
    public String pluginNamed() {
        return PluginEnum.SECURITY.getName();
    }

    private void doRefreshConfig(final SecurityConfig securityConfig) {
        tokenEndpointService.refreshCache(securityConfig);
    }
}
